package TCPServer;
import java.io.*;
import java.net.*;

import messangerServer.MulticastWorker;
import messangerTypes.ConnectRequest;
import messangerTypes.ConnectResponse;
import messangerTypes.MessageBase;
import messangerTypes.MessangerSettings;
import messangerTypes.MultiCastAnouncement;
import messangerTypes.User;
import messangerTypes.UserMessage;

/*
 *sql insert
 *INSERT INTO `mydb`.`userdb`
(`id`,
`firstName`,
`lastName`,
`password`)
VALUES
(3,
'Albert',
'Einstien',
'hello'); 
 * 
 * SELECT 'id','firstName','lastName','password'  FROM mydb.userdb WHERE lastname = 'Doe'; 
 * 
 * 
*/


class TCPServer
{
   public static void main(String argv[]) throws Exception
   {
	   MulticastWorker mw = new MulticastWorker ();
	   
	   mw.join();
	   mw.start();
	   
	   User one = new User("jane","doe", 0, "");
	   User two = new User("john","doe", 1, "");
	   User three = new User("frank","henderson", 2, "");
	   User four = new User("idont","givafuc", 3, "");
	   
	   mw.addUser(one);
	   mw.addUser(two);
	   mw.addUser(three);
	   mw.addUser(four);
	   
	   ServerSocket welcomeSocket = new ServerSocket(6789);
	   
	   while(true)
	   {
		   Socket connectionSocket = welcomeSocket.accept();

		   ObjectInputStream inFromClient = new ObjectInputStream (connectionSocket.getInputStream());
		   ObjectOutputStream outToClient = new ObjectOutputStream (connectionSocket.getOutputStream());

		   while(true)
		   {

			   try
			   {
				   MessageBase mb = (MessageBase)inFromClient.readObject();
				   System.out.println("Server: read object from stream");
				   switch (mb.getType())
				   {
				   case CONNECT_REQUEST:
					   ConnectRequest req = (ConnectRequest)mb;
					   ConnectResponse cr;

					   if(req.isLogin())
					   {
						   req.getRequestingUser().setId(5);
						   cr = new ConnectResponse(ConnectResponse.ResponseCode.ACCEPTED, req.getRequestingUser());
						   mw.addUser(req.getRequestingUser());
					   }
					   else
					   {
						   cr = new ConnectResponse(ConnectResponse.ResponseCode.ACCEPTED, req.getRequestingUser(), req.getRequestedUser());
					   }
					   outToClient.writeObject(cr);
					   break;
				   case CONNECT_RESPONSE:
					   break;
				   case KEEP_ALIVE:
					   break;
				   case MULTICAST_ANOUNCMENT:
					   break;
				   case USER_MESSAGE:
					   UserMessage um = (UserMessage)mb;
					   UserMessage echo = new UserMessage(um.getDestination(), um.getSource(), um.getMessage());
					   System.out.println(um.toString());
					   System.out.println(echo.toString());
					   outToClient.writeObject(echo);
					   break;
				   case NULL:
				   default:
					   break;
				   }
			   }catch (Exception e)
			   {
				   break;
			   }
		   }

	   }
   }
}